﻿using Azure;
using Azure.Core;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
    private readonly IWeChatAuthService _weChatAuthService;
    private readonly ISessionManager _sessionManager;
    private readonly ILogger<AuthController> _logger;

    public AuthController(
        IWeChatAuthService weChatAuthService,
        ISessionManager sessionManager,
        ILogger<AuthController> logger)
    {
        _weChatAuthService = weChatAuthService;
        _sessionManager = sessionManager;
        _logger = logger;
    }


    [HttpGet("auth-url")]
    public async Task<IActionResult> GetAuthUrl([FromQuery] string returnUrl)
    {
        try
        {
            //若前台没有传入网页，则通过如下语句返回调用业务
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = $"{Request.Scheme}://{Request.Host}";//协议+域名；【设置的默认主页】
            }
             

            _logger.LogInformation("生成授权URL - 返回地址: {ReturnUrl}", returnUrl);

            var authUrl = await _weChatAuthService.GenerateAuthUrlAsync(returnUrl);

            return Ok(new
            {
                url = authUrl,
                returnUrl = returnUrl
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成授权URL失败");
            return BadRequest(new { code = 400, message = "生成授权URL失败: " + ex.Message });
        }
    }

    [HttpGet("callback")]
    public async Task<IActionResult> Callback([FromQuery] string code, [FromQuery] string state)
    {
        try
        {
            _logger.LogInformation("收到微信授权回调 - Code: {Code}, State: {State}", code, state);

            if (string.IsNullOrEmpty(code))
            {
                _logger.LogWarning("微信授权回调缺少code参数");
                return BadRequest(new { code = 400, message = "缺少授权码参数" });
            }

            var result = await _weChatAuthService.ProcessAuthorizationAsync(code, state);

            if (result.Success && result.Session != null)
            {
                // 设置会话Cookie
                SetSessionCookie(result.Session.SessionId);

                _logger.LogInformation("用户授权成功: OpenId={OpenId}", result.Session.OpenId);

                // 返回成功响应
                return Ok(new
                {
                    code = 200,
                    success = true,
                    sessionId = result.Session.SessionId,
                    user = result.UserInfo,  // 使用 UserInfo
                    returnUrl = result.ReturnUrl
                });
            }

            return BadRequest(new { code = 400, message = "授权处理失败" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "微信授权回调处理失败");
            return BadRequest(new { code = 400, message = ex.Message });
        }
    }

    [HttpGet("check-session")]
    public async Task<IActionResult> CheckSession()
    {
        _logger.LogInformation("{DateTime}------------------------------------CheckSession---begin: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

        //_logger.LogInformation("------------------------------------CheckSession---begin: ");


        var sessionId = Request.Cookies["ltweixin_session"];
        if (string.IsNullOrEmpty(sessionId))
        {
            //Response.Cookies.Append("ltweixin_session_check", "ltweixin_session_check_VALUE", new CookieOptions
            //{
            //    HttpOnly = true,
            //    Secure = false, // HTTP 环境下必须是 false
            //    SameSite = SameSiteMode.Lax, // 比 Strict 宽松，兼容性更好
            //    Expires = DateTime.UtcNow.AddHours(1),
            //    Path = "/"
            //});


           // _logger.LogInformation("{DateTime}------------------------------------CheckSession---end: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));


            return Ok(new { authenticated = false });
        }

        var isValid = await _sessionManager.ValidateSessionAsync(sessionId);
        if (isValid)
        {
            var session = await _sessionManager.GetSessionAsync(sessionId);
            return Ok(new
            {
                authenticated = true,
                user = session?.UserInfo
            });
        }

        return Ok(new { authenticated = false });
    }

    [HttpPost("refresh-session")]
    public async Task<IActionResult> RefreshSession()
    {
        var sessionId = Request.Cookies["ltweixin_session"];
        if (string.IsNullOrEmpty(sessionId))
        {
            return BadRequest(new { code = 400, message = "未找到会话" });
        }

        var success = await _sessionManager.RefreshSessionAsync(sessionId);
        if (success)
        {
            return Ok(new { code = 200, message = "会话刷新成功" });
        }

        return BadRequest(new { code = 400, message = "会话刷新失败" });
    }

    [HttpPost("logout")]
    public async Task<IActionResult> Logout()
    {
        var sessionId = Request.Cookies["ltweixin_session"];
        if (!string.IsNullOrEmpty(sessionId))
        {
            await _sessionManager.RemoveSessionAsync(sessionId);
        }

        Response.Cookies.Delete("ltweixin_session");
        return Ok(new { code = 200, message = "退出成功" });
    }

    private void SetSessionCookie(string sessionId)
    {
        _logger.LogInformation("SetSessionCookie---being: sessionId={0}", sessionId);

        Response.Cookies.Append("ltweixin_session", sessionId, new CookieOptions
        {
            HttpOnly = false,// HttpOnly=true，JavaScript 是无法读取的
            Secure = false, // HTTP 环境下必须是 false
            SameSite = SameSiteMode.Lax,
            Expires = DateTimeOffset.UtcNow.AddMinutes(20),
            Path = "/"
        });

         

        _logger.LogInformation("SetSessionCookie---end: ");


    }
}